<template>
  <view class="oto-form-item">
    <view class="oto-form-item-body">
      <view class="form-item-title">
        {{ !customTitle ? title : '' }}
        <slot name="title"></slot>
      </view>
      <slot name="title"></slot>
      <slot name="content"></slot>
    </view>
    <view class="oto-form-item-error" v-if="errMsg"> {{ errMsg }} </view>
  </view>
</template>

<script>
  import * as otoUtils from '@/components/utils/index';

  export default {
    name: 'OtoFormItem',
    inject: {
      otoForm: {
        default() {
          return null;
        }
      }
    },
    props: {
      customTitle: {
        type: Boolean,
        default: false
      },
      title: {
        type: String,
        default: '默认标题'
      },
      prop: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        errMsg: '',
        rules: null
      };
    },
    mounted() {
      // 兼容所有小程序
      this.$otoForm = otoUtils.$parent(this, 'OtoForm');
      if (this.$otoForm && this.prop) {
        // 注册到oto-form
        this.$otoForm.registryItem(this);
        // 获取规则
        if (this.getRules()) {
          const rules = this.$otoForm.rules[this.prop];
          console.log(rules.pattern);
          this.rules = rules;
        }
      }
    },
    methods: {
      validate({ value }, cb) {
        if (!this.prop) return;
        value = value || this.$otoForm.model[this.prop];
        if (this.getRules()) {
          if (this.rules.pattern && !new RegExp(this.rules.pattern).test(value)) {
            this.errMsg = this.rules.errMsg;
            typeof cb === 'function' && cb(this.errMsg);
            return;
          }

          if (this.rules.require && !value) {
            this.errMsg = this.rules.errMsg || '内容不能为空';
            typeof cb === 'function' && cb(this.errMsg);
            return;
          }
        }

        this.errMsg = '';
        typeof cb === 'function' && cb(this.errMsg);
      },
      // 检查oto-form的rules属性是否存在
      getRules() {
        if (this.$otoForm && this.$otoForm.rules && Object.keys(this.$otoForm.rules).length > 0) {
          return true;
        }
        return false;
      }
    },
    // 组件销毁前，将item从oto-form中的items移除
    beforeDestroy() {
      // 如果当前没有prop的话表示当前不要进行删除
      if (this.$otoForm && this.prop) {
        this.$otoForm.items.map((item, index) => {
          if (item === this) this.$otoForm.items.splice(index, 1);
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .oto-form-item {
    position: relative;
    .oto-form-item-body {
      .form-item-title {
        color: rgba(70.13, 70.13, 70.13, 1);
        font-size: 32rpx;
        font-weight: 700;
        font-family: 'Microsoft YaHei';
        margin-bottom: 38rpx;
      }
    }
    .oto-form-item-error {
      position: absolute;
      font-size: 24rpx;
      line-height: 24rpx;
      color: red;
      margin-top: 12rpx;
    }
  }
</style>
